var mongoose = require('mongoose');
var Cate=require("../models/mod_cate");


//新增节点
exports.cate_create=function(req, res, next) {
    const cate = new Cate(req.body);
    cate.save().then(data=>{
        find(res,req.body.type);
    });
};
//修改
exports.cate_update=function(req, res, next) {
    const id=req.body._id;
    Cate.findByIdAndUpdate(id,{$set:{text:req.body.text}},{new:true}).then(data=>{
        find(res,req.body.type);
    });
};
//删除选中
exports.cate_remove=function(req, res, next) {
    const id=req.body.ids;
    var as=id.split(",");
    if(as.length>0){
        Cate.remove({_id:{$in:as}}).then(data=>{
            find(res,req.body.type);
        });
    }
};
//删除整个
exports.cate_delete=function(req, res, next) {
         const type=req.body.id;
        console.log(req.body,req.body==undefined);
         Cate.remove({type}).then(data=>{
            console.log(data);
         });
};
//获取单个,返回的是树
exports.cate_get=function(req, res, next) {
    const id=req.params.id;
    // console.log(id);
    Cate.findById(id).then(data=>{
        find(res,id);
    });
};

//获取单个,返回的表单数据
exports.cate_ls=function(req, res, next) {
    const id=req.params.id;
    // console.log(id);
    Cate.findById(id).then(data=>{
        // find(res,id);
        res.json(data);
    });
};
//获取单个,返回的表单数据
exports.cate_lss=function(req, res, next) {
    const id=req.params.id;
    // console.log(id);
    Cate.find({parentId:id}).then(data=>{
        // find(res,id);
        res.json(data);
        // console.log(data);
    });
};
//新闻模块需求
exports.cate_gets=function(req, res, next) {
    const id=req.params.id;
    // console.log(id);
    Cate.findById(id).then(data=>{
        res.json(data);
    });
};
exports.cate_list=function(req, res, next) {
    const type=req.body.type;
    Cate.find({type}).then(data=>{
        if(data==""){
            const cate = new Cate(req.body);
            cate.save().then((data) => {
                var arr=[];
                arr.push(data)
                res.json(reverseTree(arr,null));
            });
        }else{
            res.json(reverseTree(data,null));
        }
    })
};

function find(res,type){
    // console.log(type)
    Cate.find({type}).then(data=>{
         res.json(reverseTree(data,null));
    })
}

function reverseTree(data,pid){
    var arr=[],
    temp
    var data=JSON.parse(JSON.stringify(data))//转化成能自己新增的json Object
    for(var i in data){
        if(data[i].parentId==pid){
            arr.push(data[i]);
            temp=reverseTree(data,data[i]._id);
            // console.log(temp)
            if(temp.length>0){
                data[i].children=temp;
            }
        }
    }
    return arr;
}